package com.zhouixi.handler;
import com.alibaba.fastjson.JSONObject;
import com.zhouixi.entity.Message;
import com.zhouixi.repository.NodeRegistry;
import com.zhouixi.service.MessageService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.util.concurrent.ConcurrentHashMap;


/***
 * 会话处理器
 */
@Component
@Slf4j
public class MessageHandler extends TextWebSocketHandler {

    @Resource
    private MessageService messageService ;

    @Resource
    private WebSocketHandler webSocketHandler ;

    @Resource
    private HeartbeatMessageHandler heartbeatMessageHandler ;

    @Resource
    private NodeRegistry nodeRegistry ;


    /** 创建会话时 */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        Long userId = userCast(session.getUri().getQuery().split("=")[1]);
        webSocketHandler.registerSession(userId, session);
        heartbeatMessageHandler.registerLastActiveTime(userId);
        nodeRegistry.registerNode(userId);
    }

    /** 关闭会话时 */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        Long userId = extractUserId(session); // 需实现提取逻辑
        webSocketHandler.removeSession(userId);
    }

    /** 解析用户ID */
    public Long extractUserId(WebSocketSession session) {
        String query = session.getUri().getQuery();
        if (query != null && query.startsWith("userId=")) {
            return userCast(query.split("=")[1]);
        }
        return null; // 或抛出异常
    }

    /** 发送消息时 */
    @Override
    protected void handleTextMessage(WebSocketSession session,
                                     TextMessage textMessage) throws Exception {
        if (textMessage == null || textMessage.getPayload() == null) {
            return; // 无效消息
        }
        String payload = textMessage.getPayload();
        if (payload == null || payload.isEmpty()) {
            log.info("空消息");
            return; // 无效消息
        }
        Message message = JSONObject.parseObject(payload, Message.class);
        if(message == null){
            log.info("空消息");
            return;
        }
        Long receiverId = message.getReceiverId();
        Long senderId = message.getSenderId();
        if (senderId == null || receiverId == null) {
            return; // 无效消息
        }
        String content = message.getContent();
        messageService.sendMessage(senderId, receiverId, content);
    }

    private Long userCast(String userId) {
        return Long.valueOf(userId);
    }
}